<template>
  <div class="min-h-screen flex items-center justify-center bg-gradient-to-r from-blue-50 to-indigo-50">
    <a-card class="register-card shadow-2xl">
      <div class="text-center mb-8">
        <h2 class="text-3xl font-bold bg-gradient-to-r from-blue-600 to-indigo-600 bg-clip-text text-transparent">
          用户注册
        </h2>
        <p class="mt-2 text-gray-500">欢迎加入我们的系统</p>
      </div>

      <a-form 
        :model="formData" 
        :rules="rules" 
        ref="registerForm"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
      >
        <a-form-item field="username" label="用户名" class="form-item">
          <a-input
            v-model="formData.username"
            placeholder="请输入用户名"
            allow-clear
            class="rounded-lg"
          >
            <template #prefix>
              <icon-user class="text-blue-500" />
            </template>
          </a-input>
        </a-form-item>
        
        <a-form-item field="password" label="密码" class="form-item">
          <a-input-password
            v-model="formData.password"
            placeholder="请输入密码"
            allow-clear
            class="rounded-lg"
          >
            <template #prefix>
              <icon-lock class="text-blue-500" />
            </template>
          </a-input-password>
        </a-form-item>
        
        <a-form-item field="confirmPassword" label="确认密码" class="form-item">
          <a-input-password
            v-model="formData.confirmPassword"
            placeholder="请再次输入密码"
            allow-clear
            class="rounded-lg"
          >
            <template #prefix>
              <icon-lock class="text-blue-500" />
            </template>
          </a-input-password>
        </a-form-item>
        
        <a-form-item field="realName" label="真实姓名">
          <a-input
            v-model="formData.realName"
            placeholder="请输入真实姓名"
            allow-clear
          >
            <template #prefix>
              <icon-user class="text-blue-500" />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item field="mobile" label="手机号">
          <a-input
            v-model="formData.mobile"
            placeholder="请输入手机号"
            allow-clear
          >
            <template #prefix>
              <icon-phone class="text-blue-500" />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item field="email" label="邮箱">
          <a-input
            v-model="formData.email"
            placeholder="请输入邮箱"
            allow-clear
          >
            <template #prefix>
              <icon-email class="text-blue-500" />
            </template>
          </a-input>
        </a-form-item>
        
        <div class="flex flex-col space-y-3 mt-6">
          <a-button 
            type="primary" 
            @click="handleRegister" 
            :loading="loading"
            class="register-btn h-10 text-lg font-medium"
            long
          >
            注册
          </a-button>
          <div class="text-center">
            <a-link @click="goToLogin" class="text-gray-500 hover:text-blue-500">
              已有账号？返回登录
            </a-link>
          </div>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import type { FieldRule } from '@arco-design/web-vue'
import { userApi } from '@/api/user'
import { AxiosError } from 'axios'

const router = useRouter()
const registerForm = ref()
const loading = ref(false)

const formData = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  realName: '',
  mobile: '',
  email: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名' },
    { minLength: 4, message: '用户名长度不能小于4位' }
  ],
  password: [
    { required: true, message: '请输入密码' },
    { minLength: 6, message: '密码长度不能小于6位' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码' },
    {
      validator: (value: string) => value === formData.password,
      message: '两次输入的密码不一致'
    }
  ],
  realName: [
    { required: true, message: '真实姓名不能为空' }
  ],
  mobile: [
    { required: true, message: '手机号不能为空' },
    { 
      pattern: /^1[3-9]\d{9}$/, 
      message: '手机号格式不正确'
    }
  ],
  email: [
    { required: true, message: '邮箱不能为空' },
    { 
      type: 'email',
      message: '邮箱格式不正确'
    }
  ]
} as Record<string, FieldRule[]>

// 定义后端错误响应的接口
interface ApiErrorResponse {
  code: number;
  msg: string;
  data: null;
}

// 注册处理
const handleRegister = async () => {
  try {
    await registerForm.value.validate()
    loading.value = true

    const res = await userApi.register({
      ...formData,
      userType: 'WORKER' // 默认注册为工人
    })
    console.log('注册响应:', res)

    // 如果后端返回的是空数据，且没有抛出错误，就认为注册成功
    Message.success('注册成功')
    router.push('/login')
  } catch (error: unknown) {
    console.error('注册错误:', error)
    if (error instanceof Error) {
      Message.error(error.message)
    } else if (error instanceof AxiosError) {
      // 使用类型断言并添加空值检查
      const errorMsg = (error as AxiosError<ApiErrorResponse>).response?.data?.msg
      Message.error(errorMsg || '注册失败')
    } else {
      Message.error('注册失败')
    }
  } finally {
    loading.value = false
  }
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
.register-card {
  width: 500px;
  border-radius: 1rem;
  padding: 2rem;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

:deep(.arco-form-item-label-col) {
  padding-right: 12px;
  text-align: left;
}

:deep(.arco-form-item) {
  margin-bottom: 16px;
}

:deep(.arco-input-wrapper) {
  border-radius: 0.5rem;
  height: 40px;
}

:deep(.arco-btn) {
  border-radius: 0.5rem;
  transition: all 0.3s ease;
}

.register-btn {
  background: linear-gradient(to right, #3b82f6, #4f46e5);
  border: none;
}

.register-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

:deep(.arco-input-wrapper:focus-within) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

/* 添加输入框动画效果 */
:deep(.arco-input-wrapper) {
  transition: all 0.3s ease;
}

:deep(.arco-form-item-label) {
  font-weight: 500;
  color: #4b5563;
}
</style> 